/**   
 * @{#} FuncNode.java Create on 2013-8-12 上午8:28:30   
 *   
 * Copyright (c) 2012 by Baidu.   
 */
package objtable.engine.xmlnode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBException;
import javax.xml.stream.XMLStreamException;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

import objtable.engine.ExeNode;
import objtable.engine.XmlEngine;
import objtable.engine.xmlnode.gen.Calltask;

/**
 * @author <a href="mailto:zhangbo07@baidu.com">zhangbo07</a>
 * @version 1.0
 */
public class CalltaskNode extends ExeNode {
	private Calltask calltask;

	public Calltask getCalltask() {
		return calltask;
	}

	public void setCalltask(Calltask calltask) {
		this.calltask = calltask;
	}

	@Override
	public void exeNode() {
		try {
			List<TaskThread> l_t = new ArrayList<TaskThread>();
			for (String s : calltask.getTaskname()) {
				String filename = "./xmlscript/" + s + ".xml";
				String txt = Files.toString(new File(filename), Charsets.UTF_8);
				XmlEngine eng = new XmlEngine(txt);
				if (calltask.isParallel()) {
					TaskThread t = new TaskThread(s, txt);
					t.start();
					l_t.add(t);
				} else {
					eng.runXml();
				}
			}
			if (calltask.isParallel()) {
				for (TaskThread t : l_t) {
					t.join();
				}
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage());
		}
	}

	class TaskThread extends Thread {
		XmlEngine eng;

		public TaskThread(String name, String xmltxt) throws JAXBException, XMLStreamException {
			super(name);
			this.eng = new XmlEngine(xmltxt);
		}

		@Override
		public void run() {
			try {
				eng.runXml();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}

	}
}
